package com.wkbb.basic.controller.open;

import com.github.pagehelper.PageInfo;
import com.wkbb.basic.model.OrgHoliday;
import com.wkbb.basic.model.OrgHolidayItem;
import com.wkbb.basic.service.OrgHolidayService;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.RedisKeyConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.OrgHolidayDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.utils.MapUtil;
import com.wkbb.common.utils.TimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.time.YearMonth;
import java.util.*;

/**
 * @author lizhichao
 * @date 2019/8/22
 * @description
 */
@RestController
@Api(description = "组织节假日对外接口")
@RequestMapping("/basic/{apiVersion}/orgHoliday/open")
@Slf4j
public class HolidayController extends BaseController {

    @Autowired
    private OrgHolidayService orgHolidayService;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @ApiOperation("初始化节假日信息")
    @RequestMapping(value = "/initOrgHoliday", method = RequestMethod.GET)
    public ResultDTO<PageInfo<OrgHolidayDto>> initOrgHoliday(
            @ApiParam(value = "接口版本",required = true,defaultValue = "v1") @PathVariable(value = "apiVersion",required = true) String apiVersion,
            @ApiParam(value = "组织Id",required = false) @RequestParam(name = "orgId",required = false) Long orgId)
    {
        log.info("***********HolidayController.initOrgHoliday******apiVersion:{},orgId:{}", apiVersion, orgId);
        try {
            orgHolidayService.initOrgHoliday(orgId);
            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("HolidayController.initOrgHoliday**初始化节假日信息", e.getMessage());
            return new ResultDTO(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation("根据月份查询工作日和休息日")
    @RequestMapping(value = "/getOrgHolidayAndWorkDayByMonth", method = RequestMethod.GET)
    public ResultDTO<Map<String , List<String>>> getOrgHolidayAndWorkDayByMonth(
            @ApiParam(value = "接口版本",required = true,defaultValue = "v1") @PathVariable(value = "apiVersion",required = true) String apiVersion,
            @ApiParam(value = "机构id",required = true) @RequestParam(name = "orgId",required = true) Long orgId,
            @ApiParam(value = "月份",required = true) @RequestParam(name = "month",required = true) Integer month) {
        log.info("***********OrgHolidayManageController.getOrgHolidayAndWorkDayByMonth******apiVersion:{},orgId:{},month:{}", apiVersion, orgId,month);
        try {

            //获取缓存
            Map<String , List<String>> days = (Map<String , List<String>>)redisTemplateUtil.get(RedisKeyConstant.WKBB_BASIC_HOLIDAY
                    + "orgId_" + orgId + "_month_" + month);
            log.info("OrgHolidayManageController.getOrgHolidayAndWorkDayByMonth-days:{}", days);
            if(!MapUtil.isEmpty(days)){
                return new ResultDTO<>(days);
            }else {
                return new ResultDTO<>(this.getWorkDaysAndHolidays(orgId,month));
            }
        } catch (Exception e) {
            log.error("OrgHolidayManageController.getOrgHolidayAndWorkDayByMonth**根据月份查询工作日和休息日", e);
            e.printStackTrace();
            return new ResultDTO(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    /**
     *  根据月份查询工作日和休息日
     * @param orgId
     * @param month
     * @return
     * @throws Exception
     */
    private Map<String,List<String>> getWorkDaysAndHolidays(Long orgId,Integer month) throws Exception{

        Map<String ,Object> parms = new HashMap<>();
        parms.put("orgId",orgId);
        parms.put("month",month);
        List<OrgHolidayItem> orgHolidayItems = orgHolidayService.selectByMapParms(parms);
        Map<String,List<String>> days = new HashMap<>();
        //调休日
        List<String> restDays = new ArrayList();
        //调班日
        List<String> shifDays = new ArrayList();
        for(OrgHolidayItem orgHolidayItem : orgHolidayItems){
            String holidayItemStr = new SimpleDateFormat("yyyy-MM-dd").format(orgHolidayItem.getHolidayDate());
            if(orgHolidayItem.getHolidayType() == 1 || orgHolidayItem.getHolidayType() == 3){
                restDays.add(holidayItemStr);
            }
            if(orgHolidayItem.getHolidayType() == 2 || orgHolidayItem.getHolidayType() == 4){
                shifDays.add(holidayItemStr);
            }
        }
        List<String> workDays = new ArrayList();
        List<String> holiDays = new ArrayList();

        //获取周一到周五日期
        List<Date> dates = TimeUtil.getDates(Integer.valueOf(new SimpleDateFormat("yyyy").format(new Date())), month);
        //获取周末日期
        List<Date> weekendDates = TimeUtil.getWeekendDates(Integer.valueOf(new SimpleDateFormat("yyyy").format(new Date())), month);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        //获取周一到周五中的工作日和休息日
        for (Date date : dates) {
            String workDayStr = sdf.format(date);
            if(!restDays.contains(workDayStr)){
                workDays.add(workDayStr);
            }else {
                holiDays.add(workDayStr);
            }
        }
        //获取周末的工作日和休息日
        for(Date weekendDay : weekendDates){
            String weekendDayStr = sdf.format(weekendDay);
            if(shifDays.contains(weekendDayStr)){
                workDays.add(weekendDayStr);
            }else {
                holiDays.add(weekendDayStr);
            }
        }
        //工作日
        days.put("workDays",workDays );
        //节假日
        days.put("holiDays",holiDays );

        redisTemplateUtil.set(RedisKeyConstant.WKBB_BASIC_HOLIDAY + "orgId_" + orgId + "_month_" + month,
                days, RedisKeyConstant.EXPIRATION_TIME_24_HOUR);
        return days;
    }


    @ApiOperation("查询当月节假日信息")
    @RequestMapping(value = "/getOrgHolidayInfo", method = RequestMethod.GET)
    public ResultDTO<List<OrgHolidayDto>> getOrgHolidayInfo(
            @ApiParam(value = "接口版本",required = true,defaultValue = "v1") @PathVariable(value = "apiVersion",required = true) String apiVersion,
            @ApiParam(value = "组织Id",required = true) @RequestParam(name = "orgId",required = true) Long orgId,
            @ApiParam(value = "年月",required = true) @RequestParam(name = "yearMonth",required = true ) @DateTimeFormat(pattern = "yyyy-MM") YearMonth yearMonth) {
        log.info("***********OrgHolidayManageController.getOrgHolidayInfo******apiVersion:{},orgId:{},yearMonth:{}", apiVersion, orgId,yearMonth);

        try {
            //获取缓存
//            OrgHolidayDto orgHolidayDtoRedis = (OrgHolidayDto)redisTemplateUtil.get(RedisKeyConstant.WKBB_BASIC_HOLIDAY
//                    + "orgId_" + orgId + "_yearMonth_" + yearMonth);
//            log.info("OrgHolidayManageController.getOrgHolidayInfo-orgHolidayDtoRedis:{}", orgHolidayDtoRedis);
//            if(orgHolidayDtoRedis != null){
//                return new ResultDTO<>(orgHolidayDtoRedis);
//            }else {
                Map<String,Object> parms = new HashMap<>();
                parms.put("orgId", orgId);
                parms.put("yearMonth", yearMonth.toString());

                List<OrgHolidayDto> orgHolidayDtos = orgHolidayService.getHolidayByYearMonth(parms);
                if(CollectionUtils.isNotEmpty(orgHolidayDtos)){
                    return new ResultDTO<>(orgHolidayDtos);
                }else {
                    return new ResultDTO<>();
                }
//            }
        } catch (Exception e) {
            log.error("OrgHolidayManageController.getOrgHolidayInfo**查询当月节假日信息", e);
            e.printStackTrace();
            return new ResultDTO(ErrorCode.SYSTEM_EXCEPTION);
        }

    }
}
